#include "thread_pool.h"
#include "user.h"
#include "mysql/mysql.h"

#define SALT_STR_LEN 8
extern ListNode * userList;

void GenerateStr(char * str) {
    //传入的str长度要大于等于13
    int i,flag;
    str[0] = '$';str[1] = '6';str[2] = '$';
    srand(time(NULL));
    for(i = 3; i < SALT_STR_LEN + 3 ; i ++) {
        flag = rand()%3;
        switch(flag) {
        case 0: str[i] = rand()%26 + 'a'; break;
        case 1: str[i] = rand()%26 + 'A'; break;
        case 2: str[i] = rand()%10 + '0'; break;
        }
    }
    str[i] = '$';
    str[i+1] = '\0';
    printf("%s\n", str);//输出生成的随机数。
}

void register1Command(task_t * task){
    //遍历用户链表找到
    ListNode * p = userList;
    while(p){
        //如果是同一个客户端的连接
        if(p->val->peerfd == task->peerfd && p->val->login_status == LOGIN_OUT){
            user_info * user = p->val;
            //strcpy(p->val->name,task->data);
            strcpy(user->name,task->data);
            register1(user);
            return;
        }else{
            p = p->next;
        }
    }
}

void register2Command(task_t * task){
    ListNode * p = userList;
    while(p){
        //如果是同一个客户端的连接
        if(p->val->peerfd == task->peerfd && p->val->login_status == LOGIN_OUT){
            user_info * user = p->val;
            /* printf("encrypt:%s\n", p->val->encrypt); */
            /* strcpy(name,p->val->encrypt); */
            strcpy(user->encrypt,task->data);
            //client端发送的密文消息
            register2(user);
            return;
        }else{
            p = p->next;
        }
    }
}
void register1(user_info * usr){
    //接受从client发过来的用户名,存储于usr->name中
    train_t t;
    memset(&t,0,sizeof(t));
    //从MYSQL中获取用户名，若是成功就返回salt，若是失败就返回CODE
    char *ret[3] = {0};
    select_user(usr,ret);
    if(ret[0]){//如果返回名字为0
        //初始化发送失败的小火车
        t.len = 0;
        t.type = CMD_TYPE_REGISTER1_ERROR;
        puts("name already exist");
    }else{
        char salt[13] = {0};
        GenerateStr(salt);
        //初始化发送密文的小火车
        t.len = strlen(salt);
        t.type = CMD_TYPE_REGISTER1_RIGHT;
        memcpy(t.buff,salt,t.len);
    }
    //发送回应
    sendn(usr->peerfd,&t,8+t.len);
}
void register2(user_info * usr){
    //往MYSQL中加入用户信息
    //返还给client端注入消息
    train_t t;
    memset(&t,0,sizeof(t));

    //初始化注册文件表的
    char pwd[100] = {0};
    getcwd(pwd,sizeof(pwd));
    strcpy(usr->pwd,pwd);
    if(Add_user(usr)){//TODO:添加成功
        t.len = 0;
        t.type = CMD_TYPE_REGISTER2_RIGHT;
        puts("add user success");
    }else{
        t.len = 0;
        t.type = CMD_TYPE_REGISTER2_ERROR;
        puts("add user fail");
    }
    sendn(usr->peerfd,&t,8+t.len);
}
